<template lang="pug">
.article(v-loading="loading")
  .article-filter
    .article-filter-tabs
      .tab-item(v-for="item, index in tabs", :class="type == item.value ? 'active' : ''", :key="index" @click="changeTab(item)") {{item.label}}
    .article-filter-search(v-if="type == 1")
      el-input(size="small" prefix-icon="el-icon-search" v-model="searchContent" placeholder="输入标题/关键词" @change="changeSearch")
  .acticle-container(v-if="type == 1")
    .article-content
      .category-container
        .category-header
          .category-title 图片（{{total}}）
          .category-header-upload(v-if="spaceId != 1")
            .upload-info 图片大小不超过10MB
            ali-upload(@getFileInfo="getFileInfo" multiple accept="image/*")
              el-button(type="primary" size="small") 上传
        .category-body
          .category-list(ref="spacelist" :class="isHidden ? 'filter-row-bd_hide' : ''")
            .category-item 分组
            .category-item(
              v-for="item, index in spaceList"
              :class="spaceId === item.sourceMaterialSpaceId ? 'active' : ''"
              :key="index"
              @click="changeSpace(item)"
            ) {{item.spaceName}}（{{item.count}}）
          .category-handle
            el-button(name="primary" size="small" @click="addSpace") +新建
            el-button(icon="el-icon-setting" size="small" @click="showGroupModal = true")
        .category-more(v-if="isHidden" @click="isHidden = false")
          span 查看更多
          i.el-icon-arrow-down
    .article-handles(v-if="selections.length")
      .article-handles-container
        el-checkbox(v-model="checkAll" @change="changeAll") 全选
        .article-handle-info 已选择 {{selections.length}} 项内容
        .article-handle-cancel(@click="cancelAll") 取消选择
        .article-handle-ft
          .iconfont.icon-publish(@click="publishArticle")
          .iconfont.el-icon-delete(@click="delSource")
          .iconfont.icon-move-2#batch-move(@click="batchMove")
    .article-list(v-if="list.length")
      .article-item(v-for="item in list")
        .article-item-hover
          .article-item-hover-hd
            .article-item-checkbox(:class="!item.isChecked ? 'checked' : ''")
              el-checkbox(v-model="item.isChecked" @change="changeArticle($event, item)")
            .article-item-btns.checked
              .article-item-btn(@click="perview(item)")
                i.el-icon-search
              el-popover(
                trigger="hover"
              )
                .pop-item(@click="rename(item)") 重命名
                .pop-item(:id="`space_${item.sourceMaterialId}`" @click="moveGroup(item)") 移动分组
                .pop-item(@click="publishSingle(item)") 前往发布
                .pop-item(@click="delSingleArticle(item)") 删除
                .article-item-btn(slot="reference")
                  i.el-icon-more
        .article-item-cover(:style="`background-image: url(${item.fileUrl})`")
        .article-item-name(v-if="!item.showInput") {{item.name}}
        .article-item-name(v-else)
          el-input(v-model="item.name" v-focus @blur="blurInput(item)" @change="changeSourceName(item)" placeholder="请输入名称")
    .article-empty(v-else)
      img(src="../../static/images/empty_.png")
      .article-empty-txt 暂无数据...
    .article-footer(v-if="list.length")
      el-pagination(
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="currentChange"
      )
  .video-list-container(v-else)
    .video-list-hd
      .video-list-title 视频（共{{total}}条 ）
      .video-list-handles
        el-input(size="small" prefix-icon="el-icon-search" v-model="searchContent" placeholder="输入标题/关键词" @change="changeSearch")
        el-button(size="small" type ="primary" @click="addVideo") 添加
    .video-list(v-if="list.length")
      el-table(
        :data="list"
        :header-cell-style="{ fontSize: '12px', color: '#363636', background: '#DCDFE6' }"
        style="width: 100%"
        v-loading="loading"
        empty-text="未找到符合条件的内容"
      )
        el-table-column( label="名称")
          template(slot-scope="scope")
            .table-item
              .table-item-video
                video(:src="scope.row.fileUrl" controls)
              .table-item-title {{scope.row.title}}
        el-table-column( label="更新时间" prop="supplierBrand" align="center")
          template(slot-scope="scope") {{new Date(scope.row.createTime).format('yyyy-MM-dd hh:mm')}}
        el-table-column( label="操作" prop="supplierBrand" align="right")
          template(slot-scope="scope")
            .table-item.flex-end
              .iconfont.icon-publish(@click="publishVideo(scope.row)")
              .iconfont.icon-edit-1(@click="editVideo(scope.row)")
              .iconfont.el-icon-delete(@click="delSourceVideo(scope.row)")
    .article-empty(v-else)
      img(src="../../static/images/empty_.png")
      .article-empty-txt 暂无数据...
    .article-footer(v-if="list.length")
      el-pagination(
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="currentChange"
      )
  el-popover(
    v-model="visible"
    tigger="click"
    width="300"
    ref="spacePopover"
  )
    .pop-container
      .pop-group-list
        .group-item(v-for="space in spaceList")
          .group-item-bd(:class="space.isChecked ? 'active' : ''" @click="selectSpace(space)") {{space.spaceName}}
      .pop-footer
        el-button(size="small" type="primary" @click="confirmMove") 确定
        el-button(size="small" @click="visible = false") 取消
  space-group-modal(:show="showGroupModal" @close="closeGroupModal" @confirm="confirmGroup")
</template>

<script>
import { getSourceMaterialList, getSourceMaterialSpaceList, deleteSourceMaterial, updateSourceMaterialName, postAddSpace, moveSourceMaterial, postAddSourceMaterialPicture } from 'api'
import { mapActions } from 'vuex'
import aliUpload from '@/components/customUpload'
import spaceGroupModal from './components/spaceGroupModal'
export default {
  name: 'teacherMaterial',
  data () {
    return {
      tabs: [
        { label: '图文', value: 1 },
        { label: '视频', value: 2 }
      ],
      list: [],
      searchContent: '',
      type: 1,
      loading: false,
      pageSize: 14,
      currentPage: 1,
      spaceList: [],
      total: 0,
      spaceId: 0,
      isHidden: false,
      isMore: false,
      checkAll: false,
      selections: [],
      showGroupModal: false,
      visible: false,
      currentItem: {}
    }
  },
  components: {
    spaceGroupModal,
    aliUpload
  },
  methods: {
    ...mapActions([
      'changePreviewModal'
    ]),
    async getFileInfo (data) {
      try {
        let fileList = data.map(item => {
          return {
            fileId: item.fileId,
            name: '未命名图片'
          }
        })
        await this.$axios.post(postAddSourceMaterialPicture, { spaceId: this.spaceId, pictureList: fileList })
        this.$message.success('上传成功！')
        this.getSpaceList()
        this.getList()
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    addVideo () {
      let routeUrl = this.$router.resolve({
        name: 'editVideoMaterial'
      })
      window.open(routeUrl.href, '_blank')
    },
    editVideo (item) {
      let routeUrl = this.$router.resolve({
        name: 'editVideoMaterial',
        params: { id: item.sourceMaterialId }
      })
      window.open(routeUrl.href, '_blank')
      // this.$router.push({ name: 'editVideoMaterial', params: { id: item.sourceMaterialId } })
    },
    moveGroup (item) {
      this.currentItem = item
      if(this.$refs && this.$refs.spacePopover) {
        this.$refs.spacePopover.referenceElm = document.getElementById(`space_${item.sourceMaterialId}`)
        this.$refs.spacePopover.doToggle()
      }
    },
    closeGroupModal () {
      this.showGroupModal = false
    },
    confirmGroup () {
      this.getSpaceList()
      this.showGroupModal = false
    },
    selectSpace (item) {
      this.spaceList.forEach(row => {
        row.isChecked = false
      })
      item.isChecked = true
    },
    async confirmMove () {
      try {
        this.loading = true
        let item = this.spaceList.find(item => item.isChecked)
        let ids = []
        if (this.selections.length) {
          ids = this.selections.map(item => item.sourceMaterialId)
        } else {
          ids = [this.currentItem.sourceMaterialId]
        }
        await this.$axios.post(moveSourceMaterial, { targetSpaceId: item.sourceMaterialSpaceId, sourceMaterialIds: ids })
        this.currentItem = {}
        this.getSpaceList()
        this.getList()
        if (this.selections.length) this.selections = []
        this.$refs.spacePopover.doClose()
        this.loading = false
      } catch (err) {
        this.loading = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    addSpace () {
      this.$prompt('', '请输入分组名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: function (val) {
          if (!val) return '请输入分组名称'
          else if (val.length > 6) return '分组名称不能超过6个字符'
        },
        inputErrorMessage: ''
      }).then(async ({ value }) => {
        try {
          await this.$axios.post(postAddSpace, { spaceName: value })
          this.$message.success('添加成功！')
          this.getSpaceList()
        } catch (err) {
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    changeArticle (value, item) {
      if (value) {
        this.selections.push(item)
      } else {
        let index = this.selections.findIndex(row => row.sourceMaterialId === item.sourceMaterialId)
        if (index > -1) {
          this.selections.splice(index, 1)
        }
      }
    },
    rename (item) {
      this.list.forEach(row => {
        row.showInput = false
      })
      item.showInput = true
    },
    blurInput (item) {
      item.showInput = false
    },
    async changeSourceName (item) {
      try {
        await this.$axios.post(updateSourceMaterialName, { sourceMaterialId: item.sourceMaterialId, name: item.name })
        item.showInput = false
        this.$message.success('修改成功！')
        this.getList()
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    changeAll (value) {
      this.selections = []
      this.list.forEach(item => {
        item.isChecked = value
        this.changeArticle(value, item)
      })
    },
    cancelAll () {
      this.selections = []
      this.list.forEach(item => {
        item.isChecked = false
      })
    },
    publishArticle () {
      let sourceId = this.selections.map(item => item.sourceMaterialId).join(',')
      let routeUrl = this.$router.resolve({
        name: 'editArticle',
        query: { sourceId }
      })
      window.open(routeUrl.href, '_blank')
    },
    publishSingle (item) {
      let sourceId = [item.sourceMaterialId].join(',')
      let routeUrl = this.$router.resolve({
        name: 'editArticle',
        query: { sourceId }
      })
      window.open(routeUrl.href, '_blank')
    },
    publishVideo (row) {
      let sourceId = row.sourceMaterialId
      let routeUrl = this.$router.resolve({
        name: 'editVideo',
        query: { sourceId }
      })
      window.open(routeUrl.href, '_blank')
    },
    batchMove () {
      if(this.$refs && this.$refs.spacePopover) {
        this.$refs.spacePopover.referenceElm = document.getElementById(`batch-move`)
        this.$refs.spacePopover.doToggle()
      }
    },
    delSource () {
      this.$confirm(`确定删除选择的这些素材吗？`, '提示').then(async () => {
        try {
          let ids = this.selections.map(item => item.sourceMaterialId)
          await this.$axios.post(deleteSourceMaterial, { sourceMaterialIds: ids })
          this.$message.success('删除成功！')
          this.currentPage = 1
          this.getSpaceList()
          this.getList()
        } catch (err) {
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    delSingleArticle (item) {
      this.$confirm(`确定删除该素材吗？`, '提示').then(async () => {
        try {
          this.loading = true
          let ids = [item.sourceMaterialId]
          await this.$axios.post(deleteSourceMaterial, { sourceMaterialIds: ids })
          this.$message.success('删除成功！')
          this.currentPage = 1
          this.getSpaceList()
          this.getList()
          this.loading = false
        } catch (err) {
          this.loading = false
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    delSourceVideo (item) {
      this.$confirm(`删除该视频后将无法恢复，所有使用该视频的内容中所对应的视频将都会被删除。`, '提示').then(async () => {
        try {
          let ids = [item.sourceMaterialId]
          await this.$axios.post(deleteSourceMaterial, { sourceMaterialIds: ids })
          this.$message.success('删除成功！')
          this.currentPage = 1
          this.getList()
        } catch (err) {
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    perview (item) {
      this.changePreviewModal({ show: true, url: item.fileUrl })
    },
    changeSpace (item) {
      this.currentPage = 1
      this.spaceId = item.sourceMaterialSpaceId
      this.getList()
    },
    currentChange (page) {
      this.currentPage = page
      this.getList()
    },
    setMoreIcon (index) {
      this.$nextTick(() => {
        let itemHeight = this.$refs.spacelist.clientHeight
        if (itemHeight > 42) {
          this.isHidden = true
          this.isMore = true
        } else {
          this.isMore = false
        }
      })
    },
    changeTab (item) {
      this.currentPage = 1
      this.type = item.value
      this.getList()
    },
    changeSearch () {
      this.currentPage = 1
      this.getList()
    },
    async getList () {
      try {
        this.selections = []
        this.loading = true
        let query = {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
        if (this.searchContent) query.searchContent = this.searchContent
        if (this.type) query.type = this.type
        if (this.spaceId) query.spaceId = this.spaceId
        const { ResultSet } = await this.$axios.post(getSourceMaterialList, { ...query })
        if (ResultSet.userData.data.length) {
          ResultSet.userData.data.forEach(item => {
            item.showInput = false
            item.isChecked = false
          })
        }
        this.list = ResultSet.userData.data || []
        this.total = ResultSet.userData.total
        this.loading = false
      } catch (err) {
        this.loading = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getSpaceList () {
      try {
        const { ResultSet } = await this.$axios.post(getSourceMaterialSpaceList, { type: 1 })
        ResultSet.userData.data.forEach(item => {
          item.isChecked = false
        })
        this.spaceList = ResultSet.userData.data
        if (!this.spaceId) this.spaceId = ResultSet.userData.data[0].sourceMaterialSpaceId
        this.getList()
        this.setMoreIcon()
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // vm.getList()
      vm.getSpaceList()
    })
  }
}
</script>

<style lang="scss" scoped>
.article {
  width: 100%;
  padding: 0 40px 30px;
  background: #f5f5f5;
}
.article-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
}
.article-title {
  font-size: 16px;
  color: #363636;
  line-height: 22px;
}
.article-filter {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
}
.article-filter-tabs {
  display: flex;
  align-items: center;
  padding-left: 10px
}
.tab-item {
  font-size: 14px;
  line-height: 22px;
  color: #363636;
  margin-right: 50px;
  cursor: pointer;
  &.active {
    color: #ED5B75;
  }
}
.article-filter-search {
  .el-input,
  .el-input__inner {
    background: #f5f5f5 !important;
  }
}
.article-empty {
  padding-top: 80px;
  text-align: center;
}
.article-empty-txt {
  font-size: 16px;
  margin-top: 10px;
  color: #999;
}
.article-content {
  background: #fff;
}
.category-header {
  padding: 25px 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.category-title {
  font-weight: 700;
  font-size: 14px;
  line-height: 20px;
  color: #363636;
}
.category-header-upload {
  display: flex;
  align-items: center;
  .upload-info {
    font-size: 14px;
    line-height: 22px;
    color: #999;
    margin-right: 10px;
  }
}
.category-body {
  display: flex;
  padding: 15px 32px;
}
.category-list {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
  padding-right: 200px;
  &.filter-row-bd_hide {
    height: 42px;
    overflow: hidden;
  }
}
.category-item {
  padding: 8px 16px;
  font-size: 12px;
  line-height: 16px;
  color: #363636;
  cursor: pointer;
  border-radius: 20px;
  margin-right: 10px;
  margin-bottom: 10px;
  &.active {
    background: #FF2E42;
    color: #fff;
  }
}
.article-list {
  padding: 10px 12px;
  display: flex;
  flex-wrap: wrap;
  background: #fff;
}
.article-item {
  position: relative;
  margin: 0 6px 35px;
  &:hover {
    .checked {
      opacity: 1;
    }
  }
}
.article-item-hover {
  position: absolute;
  left: 0;
  top: 0;
  padding: 6px 12px;
  width: 100%;
  height: 100%;
}
.checked {
  opacity: 0;
}
.article-item-hover-hd {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.article-item-btns {
  display: flex;
  align-items: center;
}
.article-item-btn {
  width: 28px;
  height: 28px;
  border: 1px solid #DCDFE6;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 15px;
  cursor: pointer;
}
.article-item-cover {
  width: 200px;
  height: 200px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.article-footer {
  padding: 0 20px 20px;
  text-align: right;
  background: #fff;
}
.category-more {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #576B95;
  padding: 15px 0;
  cursor: pointer;
  span {
    display: inline-block;
    margin-right: 10px;
  }
}
.article-item-name {
  margin-top: 5px;
  padding: 10px 0;
  text-align: center;
  font-size: 14px;
  line-height: 16px;
  color: #363636;
}
.article-handles {
  padding: 0 23px;
  background: #fff;
}
.article-handles-container {
  height: 48px;
  display: flex;
  align-items: center;
  background: #DCDFE6;
  padding: 0 15px;
}
.article-handle-info {
  margin-left: 30px;
  font-size: 12px;
  color: #000;
}
.article-handle-cancel {
  font-size: 12px;
  color: #999;
  margin-left: 30px;
}
.article-handle-ft {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .iconfont {
    font-size: 16px;
    color: #999;
    margin-left: 15px;
    cursor: pointer;
  }
}
.video-list-container {
  background: #fff;
  border-radius: 4px;
  .video-list-hd {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 36px 32px;
    .video-list-title {
      font-size: 14px;
      line-height: 20px;
      color: #363636;
      font-weight: 700;
    }
    .video-list-handles {
      display: flex;
      align-items: center;
      .el-button {
        margin-left: 25px;
      }
    }
  }
}
.video-list {
  padding: 15px 30px;
  .el-table {
    font-size: 12px;
  }
}
.table-item {
  display: flex;
  align-items: center;
  &.flex-end {
    justify-content: flex-end;
    .iconfont {
      margin-left: 10px;
      font-size: 16px;
      color: #999;
      cursor: pointer;
    }
  }
  .table-item-video {
    width: 135px;
    min-width: 135px;
    height: 90px;
    video {
      width: 100%;
      height: 100%;
    }
  }
  .table-item-title {
    padding-left: 10px;
    font-size: 14px;
    color: #3E4373;
    line-height: 28px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2; //行数
    -webkit-box-orient: vertical;
  }
}
.pop-item {
  padding: 10px 0;
  cursor: pointer;
}
.pop-group-list {
  display: flex;
  flex-wrap: wrap;
  max-height: 300px;
  overflow: overlay;
  .group-item {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    .group-item-bd {
      padding: 7px 16px;
      border-radius: 50px;
      color: #363636;
      font-size: 14px;
      margin-bottom: 10px;
      cursor: pointer;
      &.active {
        background: #FF2E42;
        color: #fff;
      }
    }
  }
}
.pop-footer {
  text-align: center;
}
</style>